﻿namespace uTorrentNAS.Services
{
    using System;
    using uTorrentWebAPI;

    public class TorrentService
    {
        private readonly FileService _fileService;
        private readonly ArchiveService _archiveService;
        private readonly ConfigurationService _configurationService;

        private UTorrentWebClient _client;

        public TorrentService(FileService fileService, ArchiveService archiveService, ConfigurationService configurationService)
        {
            _fileService = fileService;
            _archiveService = archiveService;
            _configurationService = configurationService;
        }

        public void Start()
        {
            var configration = _configurationService.Retrieve();

            if (configration == null)
            {
                throw new Exception("Configuration could not be retrieved");
            }

            if (_client != null)
            {
                _client.Dispose();
            }

            _client = new UTorrentWebClient(configration.UTorrentSettings.ServerAddress, configration.UTorrentSettings.Username, configration.UTorrentSettings.Password, true)
            {
                MinimumTimeBetweenUpdates = TimeSpan.FromSeconds(configration.ScannerSettings.Interval)
            };

            // possibly finished?
            _client.TorrentStopped += (sender, args) =>
            {
                if (args.Torrent.StatusCategory.HasFlag(TorrentStatusCategory.Completed) &&
                    !args.Torrent.StatusCategory.HasFlag(TorrentStatusCategory.Uploading))
                {
                    TorrentFinished(args.Torrent, configration);
                }
            };

            _client.TorrentFinishedDownloading += (sender, args) => TorrentDownloaded(args.Torrent, configration);

            configration.ScannerSettings.StartOnLaunch = true;
            _configurationService.Save(configration);
        }

        public void Stop()
        {
            var configration = _configurationService.Retrieve();

            if (_client != null)
            {
                _client.Dispose();
            }

            _client = null;

            configration.ScannerSettings.StartOnLaunch = false;
            _configurationService.Save(configration);
        }

        public bool IsStarted()
        {
            return (_client != null && _client.AutoUpdate);
        }

        public void TorrentFinished(Torrent torrent, Configuration configuration)
        {

        }

        public void TorrentDownloaded(Torrent torrent, Configuration configuration)
        {

        }
    }
}
